<!-- pages/repository.vue -->
<template>
  <div class="repository-page">
    <h1 class="page-title">
      <DatabaseOutlined />
      仓库管理
    </h1>



    <!-- 用户信息和统计区域放在第二行 -->
    <a-row :gutter="24" class="info-row">
      <a-col :span="8">
        <!-- 用户信息卡片 -->
        <a-card title="用户信息" class="user-info-card" :bordered="false">
          <template #extra>
            <UserOutlined />
          </template>
          <UserInfoCardAsync 
            :user="authStore.currentUser"
            :repository-count="repositories.length"
          />
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 快速操作区域 -->
        <a-card title="快速操作" class="quick-actions-card" :bordered="false">
          <template #extra>
            <RocketOutlined />
          </template>
          <div class="quick-actions">
            <a-button type="primary" @click="showCreateModal" size="large" class="action-btn">
              <template #icon>
                <PlusOutlined />
              </template>
              新增仓库
            </a-button>
            <a-button @click="refreshRepositories" size="large" class="action-btn">
              <template #icon>
                <ReloadOutlined />
              </template>
              刷新列表
            </a-button>
            <a-button @click="exportRepositories" size="large" class="action-btn">
              <template #icon>
                <ExportOutlined />
              </template>
              导出数据
            </a-button>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <!-- 统计信息区域 -->
        <a-card title="统计信息" class="stats-card" :bordered="false">
          <template #extra>
            <BarChartOutlined />
          </template>
          <StatsCardAsync 
            :total-repositories="repositories.length"
            :today-repositories="getTodayRepositories()"
            :recently-updated="getRecentlyUpdated()"
          />
        </a-card>
      </a-col>
    </a-row>
    <!-- 我的仓库独占一行 -->
    <a-card title="我的仓库" class="repositories-card" :bordered="false">
      <template #extra>
        <a-space>
          <a-tooltip title="刷新列表">
            <ReloadOutlined @click="refreshRepositories" />
          </a-tooltip>
          <a-tooltip title="新增仓库">
            <PlusCircleOutlined @click="showCreateModal" />
          </a-tooltip>
        </a-space>
      </template>

      <div class="table-container">
        <a-table 
          :columns="columns" 
          :data-source="repositories" 
          :loading="loading"
          :pagination="false"
          row-key="id"
          size="middle"
          :scroll="{ x: 1000 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'actions'">
              <a-space>
                <a-tooltip title="编辑仓库">
                  <a-button type="link" @click="showEditModal(record)" size="small">
                    <EditOutlined />
                  </a-button>
                </a-tooltip>
                <a-tooltip title="删除仓库">
                  <a-popconfirm title="确定要删除这个仓库吗？" @confirm="deleteRepository(record.id)">
                    <a-button type="link" danger size="small">
                      <DeleteOutlined />
                    </a-button>
                  </a-popconfirm>
                </a-tooltip>
                <a-tooltip title="查看详情">
                  <a-button type="link" size="small" @click="showDetail(record)">
                    <EyeOutlined />
                  </a-button>
                </a-tooltip>
              </a-space>
            </template>
            <template v-else-if="column.key === 'createdAt'">
              <ClockCircleOutlined />
              {{ formatDate(record.createdAt) }}
            </template>
            <template v-else-if="column.key === 'updatedAt'">
              <SyncOutlined />
              {{ formatDate(record.updatedAt) }}
            </template>
            <template v-else-if="column.key === 'giteeUrl'">
              <a :href="record.giteeUrl" target="_blank" class="gitee-link">
                <GithubOutlined />
                {{ formatUrl(record.giteeUrl) }}
              </a>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record)" class="status-tag">
                <BulbOutlined />
                {{ getStatusText(record) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'remark'">
              <span class="remark-text">{{ record.remark || '无备注' }}</span>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="pagination.total"
          show-size-changer
          show-quick-jumper
          :show-total="total => `共 ${total} 条记录`"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
        />
      </div>
    </a-card>
    <!-- 异步加载的仓库模态框 -->
    <RepositoryModalAsync
      v-model:visible="modalVisible"
      :is-editing="isEditing"
      :editing-data="editingData"
      :loading="editLoading"
      @submit="handleModalSubmit"
      @cancel="handleModalCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import {
  DatabaseOutlined,
  PlusOutlined,
  PlusCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  GithubOutlined,
  UserOutlined,
  ReloadOutlined,
  ExportOutlined,
  BarChartOutlined,
  EyeOutlined,
  BulbOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  RocketOutlined
} from '@ant-design/icons-vue'

// 使用异步组件
const { RepositoryModalAsync, UserInfoCardAsync, StatsCardAsync } = useAsyncComponents()

interface Repository {
  id: number
  giteeUrl: string
  remark?: string
  createdAt: string
  updatedAt: string
  userId: number
}

interface Pagination {
  current: number
  pageSize: number
  total: number
}

const authStore = useAuthStore()
const repositories = ref<Repository[]>([])
const loading = ref(false)

// 模态框状态
const modalVisible = ref(false)
const isEditing = ref(false)
const editingData = ref<Partial<Repository>>({})
const editLoading = ref(false)

// 分页配置
const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60,
    fixed: 'left'
  },
  {
    title: '仓库地址',
    dataIndex: 'giteeUrl',
    key: 'giteeUrl',
    width: 200,
    ellipsis: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 150,
    ellipsis: true
  },
  {
    title: '状态',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 120
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right'
  }
]

// 获取仓库列表
const fetchRepositories = async () => {
  loading.value = true
  try {
    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      message.error('请先登录')
      return
    }

    const response = await $fetch('/api/repositories', {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        username: currentUser.username,
        page: pagination.current,
        limit: pagination.pageSize
      }
    })

    if (response.code === 200) {
      repositories.value = response.data.repositories || []
      pagination.total = response.data.pagination?.totalCount || repositories.value.length
    }
  } catch (error: any) {
    console.error('获取仓库列表失败:', error)
    message.error(error.data?.message || '获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建模态框
const showCreateModal = () => {
  isEditing.value = false
  editingData.value = {}
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record: Repository) => {
  isEditing.value = true
  editingData.value = { ...record }
  modalVisible.value = true
}

// 处理模态框提交
const handleModalSubmit = async (submitData: any) => {
  try {
    editLoading.value = true
    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      message.error('请先登录')
      return
    }

    const requestData = {
      username: currentUser.username,
      giteeUrl: submitData.giteeUrl,
      remark: submitData.remark
    }

    if (isEditing.value && submitData.id) {
      // 更新操作
      await $fetch(`/api/repositories/${submitData.id}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: requestData
      })
      message.success('仓库更新成功')
    } else {
      // 新增操作
      await $fetch('/api/repositories', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: requestData
      })
      message.success('仓库创建成功')
    }

    modalVisible.value = false
    fetchRepositories() // 刷新列表
  } catch (error: any) {
    console.error('操作失败:', error)
    message.error(error.data?.message || '操作失败')
  } finally {
    editLoading.value = false
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  editingData.value = {}
}

// 删除仓库
const deleteRepository = async (id: number) => {
  try {
    const token = authStore.token
    const currentUser = authStore.currentUser

    if (!token || !currentUser) {
      message.error('请先登录')
      return
    }

    await $fetch(`/api/repositories/${id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      query: {
        username: currentUser.username
      }
    })

    message.success('仓库删除成功')
    fetchRepositories() // 刷新列表
  } catch (error: any) {
    console.error('删除失败:', error)
    message.error(error.data?.message || '删除失败')
  }
}

// 查看详情
const showDetail = (record: Repository) => {
  // 可以打开详情页或显示详情弹窗
  message.info(`查看仓库详情: ${record.giteeUrl}`)
}

// 其他原有方法保持不变...
const refreshRepositories = () => {
  pagination.current = 1
  fetchRepositories()
  message.success('刷新成功')
}

const exportRepositories = () => {
  message.info('导出功能开发中...')
}

const getStatusColor = (record: Repository) => {
  const now = new Date()
  const updatedAt = new Date(record.updatedAt)
  const diffDays = (now.getTime() - updatedAt.getTime()) / (1000 * 3600 * 24)

  if (diffDays < 7) return 'green'
  if (diffDays < 30) return 'orange'
  return 'red'
}

const getStatusText = (record: Repository) => {
  const now = new Date()
  const updatedAt = new Date(record.updatedAt)
  const diffDays = (now.getTime() - updatedAt.getTime()) / (1000 * 3600 * 24)

  if (diffDays < 7) return '活跃'
  if (diffDays < 30) return '一般'
  return '停滞'
}

const formatUrl = (url: string) => {
  if (url.length > 30) {
    return url.substring(0, 27) + '...'
  }
  return url
}

const formatDate = (dateString: string) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getTodayRepositories = () => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return repositories.value.filter(repo => {
    const repoDate = new Date(repo.createdAt)
    return repoDate >= today
  }).length
}

const getRecentlyUpdated = () => {
  const weekAgo = new Date()
  weekAgo.setDate(weekAgo.getDate() - 7)
  return repositories.value.filter(repo => {
    const repoDate = new Date(repo.updatedAt)
    return repoDate >= weekAgo
  }).length
}

const handlePageChange = (page: number, pageSize?: number) => {
  pagination.current = page
  if (pageSize) {
    pagination.pageSize = pageSize
  }
  fetchRepositories()
}

const handleSizeChange = (current: number, size: number) => {
  pagination.current = 1
  pagination.pageSize = size
  fetchRepositories()
}

// 页面加载时获取数据
onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchRepositories()
  }
})

// 监听认证状态变化
watch(() => authStore.isAuthenticated, (newVal) => {
  if (newVal) {
    fetchRepositories()
  }
})

useHead({
  title: '仓库管理 - 系统控制台'
})
</script>

<style scoped>
/* 原有样式保持不变，只需确保样式正确应用 */
.repository-page {
  min-height: 100vh;
  padding: 24px;
  background-image: url('~/assets/images/bgcar.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-title {
  text-align: center;
  color: #fff;
  font-size: 2.5rem;
  margin-bottom: 32px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.repositories-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
}

.repositories-card :deep(.ant-card-head) {
  border-bottom: 1px solid #e8e8e8;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.repositories-card :deep(.ant-card-extra) {
  color: white;
}

.table-container {
  margin: 16px 0;
}

.gitee-link {
  color: #1890ff;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 6px;
}

.gitee-link:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.remark-text {
  color: #666;
  font-style: italic;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.info-row {
  margin-top: 0;
}

.user-info-card,
.quick-actions-card,
.stats-card {
  margin-bottom: 0;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  height: 100%;
}

.user-info-card :deep(.ant-card-head),
.quick-actions-card :deep(.ant-card-head),
.stats-card :deep(.ant-card-head) {
  border-bottom: 1px solid #e8e8e8;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.user-info-card :deep(.ant-card-extra),
.quick-actions-card :deep(.ant-card-extra),
.stats-card :deep(.ant-card-extra) {
  color: white;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

.action-btn {
  height: 40px;
  font-size: 14px;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .repository-page {
    padding: 16px;
  }

  .info-row .ant-col-8 {
    width: 100%;
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
    margin-bottom: 24px;
  }

  .quick-actions {
    flex-direction: column;
  }

  .action-btn {
    width: 100%;
  }

  .table-container {
    overflow-x: auto;
  }
}
</style>